﻿using System;
using System.IO;
using System.Media;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel.Security.Tokens;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using BTM_Client_DBwork.Constants;
using FluentNHibernate.Utils;

namespace BTM_Client_Application.SupportClasses
{
    static class SoundsWorker
    {
        public static bool IsSoundEnabled { get; set; }

        static SoundPlayer _alarmPlayer = new SoundPlayer();
        static SoundPlayer _messagePlayer = new SoundPlayer();

        static private Stream _alarmStream = (Stream) Res.Rm.GetObject("Alarm1");
        static private Stream _messageStream = (Stream)Res.Rm.GetObject("Message1");

        static private List<Task> _alarmList = new List<Task>();
        static private List<Task> _messageList = new List<Task>();

        static SoundsWorker()
        {
            IsSoundEnabled = true;
            _alarmPlayer.Stream = _alarmStream;
            _messagePlayer.Stream = _messageStream;
            try
            {
                bool se;
                if (bool.TryParse(AliveInfo.DBwork.GetParameterValue(OptionNames.SOUND_ON), out se))
                {
                    IsSoundEnabled = se;
                }

            }
            catch (Exception)
            {
                AliveInfo.DBwork.SetParameter(OptionNames.SOUND_ON, OptionDefaultValue.SOUND_ON);
            }
            
        }

        private static void ErrorPlay()
        {
            _alarmPlayer.PlaySync();
            _alarmList.Clear();
        }

        private static void MessagePlay()
        {
            _messagePlayer.PlaySync();
            _messageList.Clear();
        }

        public static void NewErrorPlay()
        {
            if (!IsSoundEnabled)
                return;
            if (_alarmList.Any())
                return;
            _alarmList.Add(new Task(ErrorPlay));
            _alarmList[0].Start();
        }

        public static void NewChatMessagePlay()
        {
            if (!IsSoundEnabled)
                return;
            if (_messageList.Any())
                return;
            _messageList.Add(new Task(MessagePlay));
            _messageList[0].Start();
        }
    }
}
